package coregui

import (
	"embed"
	"errors"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"

	"gitee.com/StarCitizen_CN/logger"
	"gitee.com/StarCitizen_CN/stargox/pkg/core"
)

var (
	//go:embed WenQuanYiMicroHei-01.ttf
	WenQuanYiMicroHeiFontFile embed.FS

	fontFilePath = filepath.Join(core.TempDir, "WenQuanYiMicroHei-01.ttf")
	isCachedFont bool
)

func SetupFont(appName string) {

	if isCachedFont {
		return
	}

	if err := core.CheckAndCrateOsTemp(); err != nil {
		logger.Err(err)
		logger.ShowGuiMsg(fmt.Sprintf("初始化%s失败", appName), "访问字体缓存目录失败。")

		return
	}

	_, err := os.Stat(fontFilePath)
	if err == nil {
		setFont()
		return
	}
	if !errors.Is(err, fs.ErrNotExist) {
		logger.Err(err)
		logger.ShowGuiMsg(fmt.Sprintf("初始化%s失败", appName), "访问字体缓存失败。")
		return
	}

	// 创建临时字体文件写入环境
	fontFile, fontTempErr := os.Create(fontFilePath)
	if fontTempErr != nil {
		logger.Err(fontTempErr)
		logger.ShowGuiMsg(fmt.Sprintf("初始化%s失败", appName), "由于系统问题导致创建字体缓存文件失败，请重新启动电脑。")
		return
	}
	defer fontFile.Close()

	data, fontEmbedErr := WenQuanYiMicroHeiFontFile.ReadFile("WenQuanYiMicroHei-01.ttf")
	if fontEmbedErr != nil {
		os.Remove(fontFilePath)
		logger.Err(fontEmbedErr)
		logger.ShowGuiMsg(fmt.Sprintf("初始化%s失败", appName), "字体文件提取异常")
		return
	}

	if _, err := fontFile.Write(data); err != nil {
		os.Remove(fontFilePath)
		logger.Err(err)
		logger.ShowGuiMsg(fmt.Sprintf("初始化%s失败", appName), "字体文件写入异常")
		return
	}

	setFont()
}

func setFont() {
	isCachedFont = true
	os.Setenv("FYNE_FONT", fontFilePath)
}

func UnsetFont() {
	isCachedFont = false
	os.Unsetenv("FYNE_FONT")
}
